package com.primeton.whdc.ccms.reportimpl.dao;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.primeton.whdc.ccms.reportimpl.entity.CallRecord;
import com.primeton.whdc.ccms.reportimpl.mapper.CallRecordMapper;
import com.primeton.whdc.ccms.reportimpl.param.ApiVO;
import com.primeton.whdc.ccms.reportimpl.param.ReportRecordVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author: YunTao.Li
 * @create: 2020-04-03 12:56
 * @description:
 **/
@Component
public class ApiCallRecordDAO {

    @Resource
    private CallRecordMapper callRecordMapper;

    public IPage<CallRecord> getCallRecordList(Map<String, Object> condition) throws Throwable {
        Long currentPage = (Long) condition.get("page");
        Long currentPageSize = (Long) condition.get("limit");

        String empCode = condition.get("empCode") != null ? condition.get("empCode").toString() : "";
        String empName = condition.get("empName") != null ? condition.get("empName").toString() : "";
        String deptCode = condition.get("deptCode") != null ? condition.get("deptCode").toString() : "";
        String appCode = condition.get("appCode") != null ? condition.get("appCode").toString() : "";
        String sysCode = condition.get("sysCode") != null ? condition.get("sysCode").toString() : "";
        String appName = condition.get("appName") != null ? condition.get("appName").toString() : "";
        String beginDate = condition.get("beginDate") != null ? condition.get("beginDate").toString() : "";
        String endDate = condition.get("endDate") != null ? condition.get("endDate").toString() : "";
        String apiName = condition.get("apiName") != null ? condition.get("apiName").toString() : "";

        IPage<CallRecord> page = new Page(currentPage, currentPageSize);

        QueryWrapper queryWrapper = new QueryWrapper();
        if (StringUtils.isNotBlank(empCode)) {
            queryWrapper.like("emp_code", empCode);
        }
        if (StringUtils.isNotBlank(sysCode)) {
            queryWrapper.like("sys_code", sysCode);
        }
        if (StringUtils.isNotBlank(appCode)) {
            queryWrapper.like("app_code", appCode);
        }
        if (StringUtils.isNotBlank(appName)) {
            queryWrapper.like("app_name", appName);
        }
        if (StringUtils.isNotBlank(deptCode)) {
            queryWrapper.like("dept_code", deptCode);
        }
        if (StringUtils.isNotBlank(empName)) {
            queryWrapper.like("emp_name", empName);
        }
        if (StringUtils.isNotBlank(apiName)) {
            queryWrapper.like("api_name", apiName);
        }
        if (StringUtils.isNotBlank(beginDate)) {
            queryWrapper.apply("UNIX_TIMESTAMP(call_time) >= UNIX_TIMESTAMP('" + beginDate + "')");
        }

        if (StringUtils.isNotBlank(endDate)) {
            queryWrapper.apply("UNIX_TIMESTAMP(call_time) <= UNIX_TIMESTAMP('" + endDate + "')");
        }

        queryWrapper.orderByDesc("call_time");

        IPage<CallRecord> callRecordIPage = callRecordMapper.selectPage(page, queryWrapper);

        return callRecordIPage;
    }

    public List<ApiVO> selectApiInfoREGEXPPath(String method, String path) throws Throwable {
        String prefix = "/ccms";
        if (StringUtils.startsWith(path, prefix)) {
            path = path.replace(prefix, "");
        }

        String beginRegExp = this.getPathBeginRegEXP(path);
        String endRegExp = this.getPathEndRegEXP(path);


        // 最后带ID
        if (endRegExp == null) {
            endRegExp = "}";
        }

        // 最后不带ID
        if (("nil").equals(endRegExp)) {
            // magic number,don't touch
            int magicNumber = 2;
            beginRegExp = beginRegExp.substring(0, beginRegExp.length() - magicNumber);

            //加入匹配符号
            beginRegExp += "[^/]";

            endRegExp = null;
        }


        System.out.println("====method:" + method + "====beginRegExp:" + beginRegExp + "========endRegExp : " + endRegExp + "=========");
        return callRecordMapper.selectApiInfoREGEXPPath(method, beginRegExp, endRegExp);
    }

    /**
     * 查询所有的api
     *
     * @return : java.util.List<com.primeton.whdc.ccms.reportimpl.param.ApiVO>
     * @author : YunTao.Li
     * @date : 2020/4/8 2020/4/8
     */
    public List<ApiVO> selectApiInfos() throws Throwable {

        //TODO : 此处因用缓存
        return callRecordMapper.selectApiInfos();
    }

    /**
     * 查询月报
     *
     * @param condition :
     * @return : java.util.List<com.primeton.whdc.ccms.reportimpl.param.ReportRecordVO>
     * @author : YunTao.Li
     * @date : 2020/8/17 2020/8/17
     */
    public List<ReportRecordVO> getMonthReport(Map<String, Object> condition) {
        String empCode = condition.get("empCode") != null ? condition.get("empCode").toString() : "";
        String deptCode = condition.get("deptCode") != null ? condition.get("deptCode").toString() : "";
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        String yrmonth = simple.format(new Date());

        if (StringUtils.isBlank(empCode)) {
            empCode = null;
        }

        if (StringUtils.isBlank(deptCode)) {
            deptCode = null;
        }

        return callRecordMapper.selectMonthReportInfos(empCode, deptCode, yrmonth);
    }

    /**
     * 查询月报
     *
     * @param condition :
     * @return : java.util.List<com.primeton.whdc.ccms.reportimpl.param.ReportRecordVO>
     * @author : YunTao.Li
     * @date : 2020/8/17 2020/8/17
     */
    public List<ReportRecordVO> getWeekReport(Map<String, Object> condition) {
        String empCode = condition.get("empCode") != null ? condition.get("empCode").toString() : "";
        String deptCode = condition.get("deptCode") != null ? condition.get("deptCode").toString() : "";

        if (StringUtils.isBlank(empCode)) {
            empCode = null;
        }

        if (StringUtils.isBlank(deptCode)) {
            deptCode = null;
        }

        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        String weekday = simple.format(new Date());
//        String weekday = "2020-08-04";
        return callRecordMapper.selectWeekReportInfos(empCode, deptCode, weekday);
    }

    /**
     * 将path拆分成匹配头，供mysql正则匹配
     *
     * @param path :
     * @return : java.lang.String[]
     * @author : YunTao.Li
     * @date : 2020/4/3 2020/4/3
     */
    protected String getPathBeginRegEXP(String path) {
        String regbegin = "/";

        String[] pathCharArray = path.split("/");
        for (String pathchar : pathCharArray) {
            if (pathchar.length() > 20) {
                break;
            } else {
                regbegin += pathchar + "/";
            }
        }
        if (regbegin.endsWith("/")) {
            regbegin = regbegin.substring(0, regbegin.length() - 1);
        }
        if (regbegin.startsWith("//")) {
            regbegin = regbegin.substring(1, regbegin.length());
        }
        regbegin += ".";
        return regbegin;
    }

    /**
     * 将path拆分成匹配头，供mysql正则匹配
     *
     * @param path :
     * @return : java.lang.String[]
     * @author : YunTao.Li
     * @date : 2020/4/3 2020/4/3
     */
    protected String getPathEndRegEXP(String path) {
        String regend = "/";
        int writeSwitch = 0;

        String[] pathCharArray = path.split("/");
        int pathCharLength = pathCharArray.length;

        for (int i = 0; i < pathCharLength; i++) {
            String pathchar = pathCharArray[i];
            if (pathchar.length() > 20) {
                writeSwitch = 1;
                continue;
            }
            if (writeSwitch == 1) {
                regend += pathchar;
            }

        }

        if (StringUtils.isBlank(regend) || ("/").equals(regend)) {
            // 最后带id
            if (writeSwitch == 1) {
                return null;
            } else {
                return "nil";
            }
        }

        regend = "." + regend;
        return regend;
    }
}
